$(function() {

    var mdEditor = editormd("mdBody", {
        width: "80%",
        height: 740,
        path: '../../app/editormd/lib/',
        theme: "default",
        previewTheme: "default",
        // editorTheme: "pastel-on-dark",
        editorTheme: "default",
        markdown: "",
        codeFold: true,
        // syncScrolling : false,
        saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
        searchReplace: true,
        // watch : false, // 关闭实时预览
        htmlDecode: "style,script,iframe|on*", // 开启 HTML 标签解析，为了安全性，默认不开启
        // toolbar : false, //关闭工具栏
        // previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
        emoji: true,
        taskList: true,
        tocm: false, // Using [TOCM]
        // tocContainer: "",
        // tocDropdown: true,
        // tocTitle: "目录",
        tex: true, // 开启科学公式TeX语言支持，默认关闭
        flowChart: true, // 开启流程图支持，默认关闭
        sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
        // dialogLockScreen : false, // 设置弹出层对话框不锁屏，全局通用，默认为true
        // dialogShowMask : false, // 设置弹出层对话框显示透明遮罩层，全局通用，默认为true
        // dialogDraggable : false, // 设置弹出层对话框不可拖动，全局通用，默认为true
        // dialogMaskOpacity : 0.4, // 设置透明遮罩层的透明度，全局通用，默认值为0.1
        // dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为#fff
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL: "/file/upload/mdImg",
        tocStartLevel: 1,
        onload: function() {
            // this.fullscreen();
            // this.unwatch();
            // this.watch().fullscreen();

            // this.setMarkdown("#PHP");
            // this.width("100%");
            // this.height(480);
            // this.resize("100%", 640);
        }
    });

    $("#save").click(function() {
        var name = $("#docName").val();
        if (null == name || name.length == 0) {
            alert("文件名称不能为空。");
            return;
        }
        var docInfo = {
            "name": name,
            "tag": $("#docTag").val(),
            "description": $("#description").val(),
            "mdDetail": mdEditor.getMarkdown(),
            "htmlDetail": mdEditor.getHTML(),
            "visibleRange": $("input:checked[name=visibleRange]").val()
        };
        var projectIds = $("#projectInput").val();
        if (2 == docInfo.visibleRange) {
            if (null != projectIds && projectIds.length > 0) {
                docInfo["projectIds"] = projectIds;
            } else {
                alert("请选择项目");
                return;
            }
        }
        $.post("/doc/create", docInfo, function(data) {
            if (data.retCode == 0) {
                alert("保存成功");
                window.location.href = "/static/html/doc/manager.html";
            } else {
                alert("保存失败:" + data.retMsg);
            }
        });
    });

    $("#showHide").click(function() {
        $("#mdBody").toggle();
    });

    $("#previewHtml").click(function() {
        mdEditor.previewing();
    });

    $(":radio").click(function(event) {
        var val = this.value;
        $("#projectDiv").hide();
        if (val == 2) {
            $("#projectDiv").show();
        }
    });

    var projectBH = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: '/project/page?searchMap[name]=%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var projects = new Array();
                    if (data.retVal.list) {
                        data.retVal.list.forEach(function(obj) {
                            projects.push({
                                'id': obj.id,
                                'name': obj.name
                            });
                        });
                    }
                    return projects;
                }
            }
        },
        remote: {
            url: '/project/page?searchMap[name]=%QUERY',
            wildcard: '%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var projects = new Array();
                    if (data.retVal.list) {
                        data.retVal.list.forEach(function(obj) {
                            projects.push({
                                'id': obj.id,
                                'name': obj.name
                            });
                        });
                    }
                    return projects;
                }
            }
        }
    });

    projectBH.initialize();

    $("#projectInput").tagsinput({
        tagClass: function(item) {
            return (item.length > 10 ? 'big' : 'small') + ' label label-warning';
        },
        itemValue: 'id',
        itemText: 'name',
        autoSelect: true,
        typeaheadjs: {
            classNames: { input: 'Typeahead-input' },
            name: 'projects',
            value: 'id',
            display: 'name',
            source: projectBH
        }
    });

});